const path = require("path");
const glob = require("glob");
const webpack = require("webpack");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const AddAssetHtmlWebpackPlugin = require("add-asset-html-webpack-plugin");
const { PurgeCSSPlugin } = require("purgecss-webpack-plugin");
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
const BundleAnalyzerPlugin =
  require("webpack-bundle-analyzer").BundleAnalyzerPlugin;

const smp = new SpeedMeasurePlugin({
  disable: !(process.env.MEASURE === "true"),
  outputFormat: "humanVerbose",
});

const PATHS = {
  src: path.join(__dirname, "src"),
};

module.exports = {
  publicPath: "./",
  parallel: true,
  configureWebpack: smp.wrap({
    module: {
      rules: [
        {
          test: /\.(gif|png|jpe?g|svg|webp)$/i,
          use: [
            {
              loader: "image-webpack-loader",
              options: {
                mozjpeg: {
                  progressive: true,
                },
                // optipng.enabled: false will disable optipng
                optipng: {
                  enabled: false,
                },
                pngquant: {
                  quality: [0.65, 0.9],
                  speed: 4,
                },
                gifsicle: {
                  interlaced: false,
                },
                // the webp option will enable WEBP
                webp: {
                  quality: 75,
                },
              },
            },
          ],
        },
      ],
    },
    cache: {
      type: "filesystem",
      cacheDirectory: path.resolve(__dirname, "./node_modules/.cache_temp"),
      name: "vue2-elm",
    },
    resolve: {
      alias: {
        src: path.resolve(__dirname, "./src"),
        assets: path.resolve(__dirname, "./src/assets"),
        components: path.resolve(__dirname, "./src/components"),
      },
    },
    // module: {
    //   rules: [
    //     {
    //       test: /\.js$/,
    //       exclude: /node_modules/,
    //       use: [
    //         {
    //           loader: "thread-loader",
    //           options: {
    //             workers: 5,
    //           },
    //         },
    //       ],
    //     },
    //   ],
    // },
    plugins: [
      new BundleAnalyzerPlugin({
        analyzerMode: process.env.MEASURE === "true" ? "json" : "disabled",
      }),
      new webpack.DllReferencePlugin({
        context: __dirname,
        manifest: path.resolve(__dirname, "./dll/vue-manifest.json"),
      }),
      new CopyWebpackPlugin({
        patterns: [
          {
            from: path.resolve(__dirname, "./dll/vue.dll.js"),
            to: path.resolve(__dirname, "./dist/js/vue.dll.js"),
          },
        ],
      }),
      new AddAssetHtmlWebpackPlugin({
        filepath: path.resolve(__dirname, "dll/vue.dll.js"),
      }),
      new PurgeCSSPlugin({
        paths: glob.sync(`${PATHS.src}/**/*`, { nodir: true }),
      }),
    ],
  }),
};
